#!/usr/bin/ruby

$max=50
$interval=0.025

def print_array( a )
  system "clear"
  $max.downto(1) {
    |line|
    for v in a do
      print v>=line ? '|' : ' '
    end
    print "\n"
  }
  sleep $interval
end

def compare( a, b )
  return a < b
end

def child( i )
  return i*2+1
end

def parent( i )
  return (i-1)/2
end

def swap( array, a, b )
  tmp=array[a]
  array[a]=array[b]
  array[b]=tmp
  print_array( array )
end
  
def siftdown( array, p, n )
  c=child(p)
  while c < n do
    c=c+1 if compare( array[c], array[c+1] )
    swap( array, p, c ) if compare(array[p], array[c] )
    p=c
    c=child(p)
  end
  swap( array, p, c ) if c==n and compare( array[p], array[c] )
end
    
def heapify( array, n )
  return if n == array.length()
  while n>0 and compare( array[parent(n)], array[n] ) do
    swap( array, n, parent(n) )
    n=parent(n)
  end
  heapify( array, n+1 )
end

def heapsort( array )
  heapify( array, 0 )
  (array.length()-1).downto(1) {
    |i|
    swap( array, 0, i )
    siftdown( array, 0, i-1 )
  }
end

a=ARGV.collect { |x| Integer(x) }
a=Array.new($max,$max).collect { |x| Integer( rand() * x ) } if a.length() == 0
print_array( a )
heapsort( a )
